package com.ywxx.dyhelper.utils;

import android.os.AsyncTask;
import android.text.TextUtils;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ywxx.dyhelper.BuildConfig;
import com.ywxx.dyhelper.model.ResponseModel;

import java.net.URLDecoder;

import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 网络请求
 */
public abstract class HttpUtils extends AsyncTask<FormBody, Integer, ResponseModel>
{
    private String url = "";
    private long starttime;

    public HttpUtils(ParamsHelper params)
    {
        url = ConstValues.URL + params.apiname;
        execute(params.ToParams());
    }

    @Override
    protected ResponseModel doInBackground(FormBody... params)
    {
        String str = "";
        FormBody body = params[0];
        for (int n = 0; n < body.size(); n++)
        {
            str += String.format("key:%s value:%s  ", body.encodedName(n), URLDecoder.decode(body.encodedValue(n)));
        }

        Log.e("httppost", str);


        ResponseModel res = new ResponseModel();
        Request request = new Request.Builder().url(url).addHeader("Connection", "close").post(body).build();// 设置post参数
        Call call = ConstValues.getInstance().getClient().newCall(request);
        Response response;
        String result = "";
        try
        {
            response = call.execute();
        } catch (Exception e)
        {
            result = e.getMessage();
            if (TextUtils.isEmpty(result) || result.contains("failed to connect to") == true || result.contains("Connection timed out") == true || result.contains("Unable to resolve host"))
            {
                res.msg = "连接网络服务器超时，请检查网络是否畅通...";
            }
            return res;
        }

        if (response.isSuccessful() == true)
        {
            try
            {
                String str_res = response.body().string();
                JSONObject resultobj = JSON.parseObject(str_res);
                if (BuildConfig.DEBUG)
                    Log.e("response", str_res);

                res.status = resultobj.getIntValue("status");
                res.msg = resultobj.getString("msg");
                res.data = resultobj.getString("data");
            } catch (Exception e)
            {
                res.msg = "服务器异常：" + e.getMessage();

            }
        } else
        {
            //解析数据失败
            res.msg = String.format("网络请求失败,请重新尝试连接(%s)...", response.code());
        }

        return res;
    }

    @Override
    protected void onPostExecute(ResponseModel responseModel)
    {
        onHttpResult(responseModel);
    }

    /**
     * 请求成功
     * @param response
     */
    public abstract void onHttpResult(ResponseModel response);


}
